import { useState } from 'react';
import { List } from 'antd';
import { SortableContainer, SortableElement } from 'react-sortable-hoc';
import React from 'react';

interface DraggableListProps {
  data: any[];
  onDragFinish?: (oldIndex: number, newIndex: number, item?: any) => void;
}

// 创建一个可排序的元素组件
const SortableItem = SortableElement(({ value }: { value: any }) => (
  <div className="list-item">{value}</div>
));

// 创建一个可排序的列表组件
const SortableList = SortableContainer(({ items }: { items: any[] }) => (
  <List className="drag-list">
    {items.map((value: any, index: number) => (
      <SortableItem key={`item-${index}`} index={index} value={value} />
    ))}
  </List>
));

// 定义一个可拖拽元素改变位置的列表组件
const DraggableList: React.FC<DraggableListProps> = ({ data, onDragFinish }) => {
  const [items, setItems] = useState<any[]>(data);

  const handleSortEnd = ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
    if (onDragFinish) {
      onDragFinish(oldIndex, newIndex, items[oldIndex]);
    }
    setItems((prevItems: any) => {
      const newItems = [...prevItems];
      const [removed] = newItems.splice(oldIndex, 1);
      newItems.splice(newIndex, 0, removed);
      return newItems;
    });
  };

  return <SortableList items={items} onSortEnd={handleSortEnd} />;
};

export default DraggableList;
